<template>
    <!-- 点赞内容分类 -->
    <div  class="header-box">
        <el-menu router :default-active="router.currentRoute.value.path" @select="handleMenuSelect">
            <el-menu-item :index="`/personalcenter/browsinghistory`">
                <span>全部</span>
            </el-menu-item>
            <el-menu-item :index="`/personalcenter/browsinghistory/BOLG`">
                <span>博客</span>
            </el-menu-item>
            <el-menu-item :index="`/personalcenter/browsinghistory/QUESTION`">
                <span>问答</span>
            </el-menu-item>
            <el-menu-item :index="`/personalcenter/browsinghistory/ESSAY`">
                <span>随记</span>
            </el-menu-item>
        </el-menu>
        <!-- 时间筛选器 -->
        <div style="display: flex; justify-content: space-between; margin-right: 20px">
            <el-radio-group v-model="selectedTimeRange" @change="handleTimeFilter">
                <el-radio-button label="TODAY">今天</el-radio-button>
                <el-radio-button label="YESTERDAY">昨天</el-radio-button>
                <el-radio-button label="THIS_WEEK">一周内</el-radio-button>
                <el-radio-button label="THIS_MONTH">一个月内</el-radio-button>
                <el-radio-button label="THREE_MONTHS">三个月内</el-radio-button>
                <el-radio-button label="EARLIER">更早</el-radio-button>
            </el-radio-group>
        </div>
    </div>
    <!-- 内容区 auto 结束-->
    <div v-if="state.isNoData" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center" >
        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 280px; height: 280px">
    </div>
    <div v-else class="autobox-container-ar">
        <!--博客列表开始-->
        <div class="blog-list">
            <!-- 卡片 -->
            <div class="blog-item" v-for="item in data.dataList" :key="item.content.contentId">
                <router-link :to="`/contentdetail/${item.content.contentType}/${item.content.contentId}`">
                    <!-- 内容主体区域 -->
                    <div class="blog-main-content">
                        <div style="display: flex; align-items: center; justify-content: space-between">
                            <!-- 标题 + 内容（左） -->
                            <div :style="item.cover ? 'width:780px' : 'width: 940px'" >
                                <strong class="blog-title">{{ item.content.title }}</strong>
                                <div class="blog-desc">{{ truncateText(stripHtml(item.content.content), 150) }}</div><!-- DOMPurify 库去除HTML标签 -->
                            </div>
                            <!-- 封面图片（右） -->
                            <div class="blog-cover" v-if="item.cover">
                                <el-image style="width: 100%; height: 100%; border-radius: 0.375rem" :src="item.content.cover" fit="cover" :preview-src-list="[item.cover]"/>
                            </div>
                        </div>
                        <!-- 文章信息区域（预留）：置于内容底部靠左-->
                        <div class="user-info-area">
                            <!-- 用户信息区域 靠左 -->
                            <el-avatar :src="item.content.user.profile_photo_path" shape="circle" :size="30" @error="errorHandler">
                                <img
                                    src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                                    alt="加载错误"/> <!--图片加载失败的回退行为-->
                            </el-avatar>
                            <div class="interaction-info">
                                <span>{{ item.content.user.username }}</span>
                                <span class="icon-item"><img src="@/assets/icon_svg/浏览量.svg" alt="icon" style="width: 20px; height: 20px">{{ item.content.views }}</span>
                                <!--                              <span class="icon-item"><img src="@/assets/icon_svg/赞.svg" alt="icon" style="width: 20px; height: 20px">{{ item.likes }}</span>-->
                                <!--                              <span class="icon-item"><img src="@/assets/icon_svg/_收藏.svg" alt="icon" style="width: 20px; height: 20px"> {{ item.collections }}</span>-->
                            </div>
                            <!--分类标签区域 靠右-->
                            <div class="blog-meta">
                                <span class="category-tag"><el-tag type="info">{{ item.content.category?.categoryName || null }}</el-tag></span>
                                <span v-if="item.tags" class="tag-list"><el-tag v-for="tag in item.tags.split(',')" :key="tag" type="success">{{ tag }}</el-tag></span>
                                <span class="publish-time">发布于{{ item.content.created_at }}</span>
                            </div>
                        </div>
                    </div>
                </router-link>
            </div>
        </div>
        <!--博客列表结束-->
        <!-- 加载更多提示 -->
        <div ref="loadMoreTip" v-if="!state.isLoading && state.hasMore" class="load-more-tip">滑动加载更多</div>
        <div v-if="state.isLoading" class="load-more-tip">加载中...</div>
    </div>
    <!-- 内容区 auto 结束-->
</template>

<script setup>
import {reactive, ref, onMounted, onUnmounted, computed} from "vue";
import DOMPurify from 'dompurify';
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
//获取本地存储中的用户信息
let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}
// 数据
const data = reactive({
    dataList: [],
})

// 状态管理
const state = reactive ({
    nextPageNum: 1, // 下一次加载的页码
    pageSize: 20, // 固定每页加载数量
    total: 0,
    isNoData: false,
    isLoading: false,
    hasMore: true, // 是否还有更多数据
})
const errorHandler = () => true //图片加载失败的回退行为
// 滚动事件处理
const loadMoreTip = ref(null);
// 加载更多
const loadMore = () => {
    if (!state.isLoading && state.hasMore) {
        loadContents(state.nextPageNum);
    }
};
const handleScroll = () => {
    if (state.isLoading || !state.hasMore) return;
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = document.documentElement.clientHeight;
    const scrollHeight = document.documentElement.scrollHeight;

    // 距离底部100px时触发加载
    if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadContents(state.nextPageNum);
    }
};
const allContent = ref([])
// 加载列表（支持无限滚动）
const loadContents = (pageNum, reset = false) => {
    state.isLoading = true;
    request.get('/api/content/selectUserBrowseHistory', {
        params: {
            pageNum,
            pageSize: state.pageSize,
            userId: user.user_id,
            timeRange: selectedTimeRange.value
        }
    }).then(res => {
        if (res.code === '200') {
            const newList = res.data.contentList;
            state.isNoData = res.data.contentList.length === 0;


            if (reset) {
                data.dataList = newList;
                allContent.value = newList;
            } else {
                // 合并新旧数据
                data.dataList = [...data.dataList, ...newList];
                allContent.value = [...allContent.value, ...newList];
            }

            // 按浏览时间降序排序
            const sortedList = data.dataList.sort((a, b) => new Date(b.browseTime) - new Date(a.browseTime));

            // 更新数据列表
            data.dataList = sortedList;
            allContent.value = sortedList; // 缓存排序后的数据

            state.total = res.data.total;
            state.nextPageNum = pageNum + 1;
            state.hasMore = newList.length === state.pageSize;
        } else {
            ElMessage.error(res.msg);
        }
    }).catch(error => {
        console.error(error);
    }).finally(() => {
        state.isLoading = false;
    });
};

// 处理内容项点击事件
const handleMenuSelect = (index) => {
    if (index === '/personalcenter/browsinghistory') {
        data.dataList = [...allContent.value];
    } else {
        const contentType = index.replace('/personalcenter/browsinghistory/', '');
        // 根据内容筛选数据
        data.dataList = allContent.value.filter(item => item.content.contentType === contentType);
    }
    state.isNoData = data.dataList.length === 0;
};

// 初始化加载
onMounted(() => {
    loadContents(state.nextPageNum);
    window.addEventListener('scroll', handleScroll);
});

// 移除滚动监听
onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
});

// 处理时间筛选
const handleTimeFilter = () => {
    // 重置分页状态
    state.nextPageNum = 1;
    state.hasMore = true;

    // 重新加载数据
    loadContents(1, true);
};

// 安全地移除HTML标签并提取纯文本
const stripHtml = (html) => {
    if (!html) return '';
    // 使用DOMPurify清理HTML，防止XSS攻击
    const clean = DOMPurify.sanitize(html);
    // 创建临时元素提取文本内容
    const temp = document.createElement('div');
    temp.innerHTML = clean;
    // 获取纯文本内容并去除多余空格
    return (temp.textContent || temp.innerText || '').trim();
};
// 截断文本并添加省略号
const truncateText = (text, length) => {
    if (text.length <= length) return text;
    // 找到最后一个完整的单词
    let truncated = text.substring(0, length);
    let lastSpace = truncated.lastIndexOf(' ');
    // 如果找到了空格，在空格处截断以避免单词被截断
    if (lastSpace !== -1) {
        truncated = truncated.substring(0, lastSpace);
    }
    return truncated + '...';
};


// 时间范围枚举
const TIME_RANGE = {
    TODAY: 'TODAY',
    YESTERDAY: 'YESTERDAY',
    THIS_WEEK: 'THIS_WEEK',
    THIS_MONTH: 'THIS_MONTH',
    THREE_MONTHS: 'THREE_MONTHS',
    EARLIER: 'EARLIER'
};

// 状态管理
const selectedTimeRange = ref(TIME_RANGE.TODAY);

// 计算属性：根据时间范围过滤的历史记录
const filteredHistoryList = computed(() => {
    if (!data.dataList || data.dataList.length === 0) {
        return [];
    }

    const now = new Date();

    return data.dataList.filter(item => {
        const createdAt = new Date(item.created_at);

        switch (selectedTimeRange.value) {
            case TIME_RANGE.TODAY:
                return isSameDay(createdAt, now);
            case TIME_RANGE.YESTERDAY:
                return isYesterday(createdAt, now);
            case TIME_RANGE.THIS_WEEK:
                return isWithinDays(createdAt, now, 7);
            case TIME_RANGE.THIS_MONTH:
                return isWithinMonths(createdAt, now, 1);
            case TIME_RANGE.THREE_MONTHS:
                return isWithinMonths(createdAt, now, 3);
            case TIME_RANGE.EARLIER:
                return !isWithinMonths(createdAt, now, 3);
            default:
                return true;
        }
    });
});

// 工具函数：判断是否同一天
const isSameDay = (date1, date2) => {
    return date1.getDate() === date2.getDate() &&
        date1.getMonth() === date2.getMonth() &&
        date1.getFullYear() === date2.getFullYear();
};

// 工具函数：判断是否昨天
const isYesterday = (date, now) => {
    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    return isSameDay(date, yesterday);
};

// 工具函数：判断是否在指定天数内
const isWithinDays = (date, now, days) => {
    const diffTime = Math.abs(now - date);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays <= days;
};

// 工具函数：判断是否在指定月数内
const isWithinMonths = (date, now, months) => {
    const diffMonths = (now.getFullYear() - date.getFullYear()) * 12 +
        (now.getMonth() - date.getMonth());
    return diffMonths <= months;
};

// 工具函数：格式化时间
const formatTimeAgo = (time) => {
    const now = new Date();
    const created = new Date(time);
    const diffMs = now - created;
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);

    if (diffSec < 60) {
        return `${diffSec}秒前`;
    } else if (diffMin < 60) {
        return `${diffMin}分钟前`;
    } else if (diffHour < 24) {
        return `${diffHour}小时前`;
    } else if (diffDay === 1) {
        return '昨天';
    } else if (diffDay < 7) {
        return `${diffDay}天前`;
    } else if (diffDay < 30) {
        return `${Math.floor(diffDay / 7)}周前`;
    } else {
        return `${Math.floor(diffDay / 30)}个月前`;
    }
};



</script>

<style scoped>
/* 导航菜单容器样式 */
.header-box {
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
}

/* 修改el-menu为横向排列 */
.el-menu {
    display: flex;
    border: none;
}

/* 菜单项样式 */
.el-menu-item {
    padding: 0 20px !important;
    height: 50px !important;
    line-height: 40px !important;
    border-bottom: 2px solid transparent;
    transition: all 0.2s;
    color: #4e5969 !important;
    font-size: 14px;
}

/* 鼠标悬停样式 */
.el-menu-item:hover {
    color: #1677ff !important;
    border-bottom-color: #1677ff;
    background-color: transparent !important;
}

/* 选中状态样式 */
.el-menu-item.is-active {
    color: #1677ff !important;
    border-bottom-color: #1677ff;
    font-weight: 500;
}

/* 移除默认的高亮背景 */
.el-menu-item:focus, .el-menu-item:hover {
    background-color: transparent !important;
}
/*中间内容区域容器：*/
.autobox-container-ar {
    position: absolute;
    /*right: 267px;*/
    width: 970px;
    box-sizing: border-box;
    background-color: #fffefb;
    min-height: 80vh;
    top: 55px;
    left: 0;
}

/*卡片样式*/
.blog-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    gap: 22px;
    padding: 20px;
    border-bottom: 2px #f5f4f1 solid;
    transition: transform 0.3s, box-shadow 0.3s;
}
.blog-item:hover {
    background-color: #f5f4f1;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.10); /* 轻微外阴影 */
}
/* 用户信息区域样式 */
.user-info-area {
    width: 100%;
    display: flex;
    align-items: center;
}

/* 内容主体区域样式 */
.blog-main-content {
    display: flex;
    flex-direction: column;
}

/*标题样式*/
.blog-title {
    font-size: 18px;
    font-weight: 600;
    color: #1a1a1a;
}
/*内容样式*/
.blog-desc {
    font-size: 14px;
    line-height: 1.6;
    color: #4f4f4f;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 限制3行 */
    padding: 15px 0;
}

/* 封面图片样式 */
.blog-cover {
    flex: 0 0 180px; /* 固定宽度，不随内容缩放 */
    display: flex;
    align-items: center;
    width: 140px;
    height: 70px;
    position: absolute;
    right: 10px;
}

/*分类标签样式*/
.blog-meta {
    position: absolute;
    right: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 14px;
    color: #666;
    margin-left: 10px;
}

/*互动信息区样式*/
.interaction-info {
    display: flex;
    align-items: center;
    gap: 20px;
    font-size: 14px;
    color: #666;
    margin-left: 10px;
}
.icon-item {
    display: flex;
    align-items: center;
    gap: 5px;
}

/* 加载提示样式 */
.load-more-tip {
    width: 100%;
    height: 50px;
    line-height: 50px;
    text-align: center;
    color: #666;
    font-size: 0.95em;
    padding: 16px;
    border-top: 1px solid #f0f0f0;
}
</style>